<?php

use Illuminate\Database\Capsule\Manager as DB;

class CorpController extends CommonController
{
    private $corp;

    public function init()
    {
        parent::init();
        $code = $this->get('code/s');
        if(empty($code)){
            throw new Exception("公司代码为空");
        }
        $corp = (new companyModel)->where('code', $code)->first()->toArray();
        if($corp) {
            $this->corp = $corp;
            $this->_view->assign('dataset', object_to_array($corp));
            $dba = 'products_' . $corp['db'];
            $products = DB::table($dba)->where('company_id', $corp['id'])->where('status', 1)->orderBy('created_at', 'desc')->limit(7)->get()->toArray();
            $this->_view->assign('products', object_to_array($products));
            $goodsnum = DB::table($dba)->where('company_id', $corp['id'])->whereIn('status', [1,2])->count();
            $this->_view->assign('goodsnum', $goodsnum);
            #dump(object_to_array($products)); exit;
        }else{
            throw new Exception('404 not found', 404);
        }
    }

    public function indexAction(){
        $this->_view->display('corp/index.html');
    }

    public function infoAction(){
        $this->_view->display('corp/info.html');
    }

    public function productsAction(){
        if($this->corp) {
            $dba      = 'products_' . $this->corp['db'];
            $page = $this->get('page', 1);
            $offset = ($page-1)*10;
            $allproducts = DB::table($dba)->where('company_id', $this->corp['id'])
                            ->whereIn('status', [1, 2])
                            ->orderBy('created_at', 'desc')
                            ->offset($offset)
                            ->limit(10)
                            ->get()
                            ->toArray();
            $total = DB::table($dba)->where('company_id', $this->corp['id'])->whereIn('status', [1, 2])->count();
            $this->_view->assign('pager', $total>0 ? (new Pager($total, 10, $page))->getPager() : '');
            $this->_view->assign('allproducts', object_to_array($allproducts));
        }

        $this->_view->display('corp/products.html');
    }

    public function newsAction(){
        $this->_view->display('corp/news.html');
    }

    public function businessAction(){
        $this->_view->display('corp/business.html');
    }

    public function contactAction(){
        $this->_view->display('corp/contact.html');
    }

}
